<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;
use app\services\ScoreService;

class Award
{
    protected $order;
    protected $user;

    protected $set;

    // 重新计算佣金
    protected $is_reset;

    // 保存直推奖金
    protected $bao_commission = 0;

    public function __construct(Order $order, $is_reset = false)
    {
        $this->is_reset = $is_reset;

        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->set = SetUserUp::getLastOne();

        $is_bao = ProductArea::checkBao($product_id);
        $is_buy = ProductArea::checkBuy($product_id);
        $is_repeat = ProductArea::checkRepeat($product_id);

        // 如果使用了积分, 则不返佣
        // $use_score = $this->order->use_score > 0;
        // if ($use_score) {
        //     return;
        // }

        // var_dump($use_score);exit;


        if ($is_bao) {
            // $this->recommend();
            $this->bao();
            // $this->baoDiff();
        }

        if ($is_buy) {
            $this->buy();
        }

        // 复购区
        if ($is_repeat) {
            $this->diff();

            // 送积分
            $this->_score();
        }


    }

    private function _score()
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();
        $score = 0;
        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $score += ($product['score']) * $item['quantity'];
        }

        $this->saveCommission($this->user->id, 0, '71', '送酉豆', $score);
    }

    public function bao()
    {
        $award_name = '推荐';
        $award_type = 21;

        $r = Chain::getReferrer($this->user->id, true);

        if ($r) {
            $amount = $this->order->total_pay - $this->order->total_freight;

            if ($amount >= $this->set->vip3) {

                $product = 0;
                $score = 0;
                $balance = 0;
                if ($r->level == UserLevel::$keys['vip3']) {
                    $balance = $this->set->vip3_vip3_balance;
                    $score = $this->set->vip3_vip3_score;
                    $product = $this->set->vip3_vip3_product;
                } else if ($r->level == UserLevel::$keys['vip2']) {
                    $balance = $this->set->vip2_vip3_balance;
                    $score = $this->set->vip2_vip3_score;
                    $product = $this->set->vip2_vip3_product;
                } else if ($r->level == UserLevel::$keys['vip1']) {
                    $balance = $this->set->vip1_vip3_balance;
                    $score = $this->set->vip1_vip3_score;
                    $product = $this->set->vip1_vip3_product;
                }

                if (!$this->is_reset) {
                    $r->quota1 += $product;
                    $r->save();
                }

                $this->bao_commission = $balance;

                $this->saveCommission($r->id, $balance, $award_type, $award_name, $score);

            }
            else if ($amount >= $this->set->vip2) {

                // 配额回本
                // var_dump($r->quota2);exit;
                if ($r->quota2 > 0) {

                    $r->quota2 -= 1;
                    $r->save();

                    $this->saveCommission($r->id, $amount, '23', '配额回本', 0);

                } else {

                    $product = 0;
                    $score = 0;
                    $balance = 0;
                    if ($r->level == UserLevel::$keys['vip3']) {
                        $balance = $this->set->vip3_vip2_balance;
                        $score = $this->set->vip3_vip2_score;
                        $product = $this->set->vip3_vip2_product;
                    } else if ($r->level == UserLevel::$keys['vip2']) {
                        $balance = $this->set->vip2_vip2_balance;
                        $score = $this->set->vip2_vip2_score;
                        $product = $this->set->vip2_vip2_product;
                    } else if ($r->level == UserLevel::$keys['vip1']) {
                        $balance = $this->set->vip1_vip2_balance;
                        $score = $this->set->vip1_vip2_score;
                        $product = $this->set->vip1_vip2_product;
                    }

                    if (!$this->is_reset) {
                        $r->quota1 += $product;
                        $r->save();
                    }

                    $this->bao_commission = $balance;

                    $this->saveCommission($r->id, $balance, $award_type, $award_name, $score);

                }


            }
        }


    }

    public function baoDiff()
    {
        $award_name = '推荐差价';
        $award_type = 22;

        $r = Chain::getReferrer($this->user->id, true);
        if (!$r) {
            return;
        }

        $chain = Chain::getReferrerChain($r->id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3']
        ], true);

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        foreach ($chain as $user) {
            if ($user->level <= $r->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diffBao($this->set->vip1_vip2_balance, $this->set->vip1_vip3_balance);
                $this->saveCommission($user->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diffBao($this->set->vip2_vip2_balance, $this->set->vip2_vip3_balance);
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diffBao($this->set->vip3_vip2_balance, $this->set->vip3_vip3_balance);
                $diff_vip3 -= $diff_vip1 + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
                break;
            }
        }


        // var_dump($diff_vip1, $diff_vip2, $diff_vip3);exit;
    }

    private function _diffBao($vip2, $vip3)
    {

        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($amount >= $this->set->vip3) {
            return $vip3 - $this->bao_commission;
        } else if ($amount >= $this->set->vip2) {
            return $vip2 - $this->bao_commission;
        }

        return 0;


    }

    // 复购差价奖
    public function diff()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
        ], true);

        $award_name = '差价';
        $award_type = 3;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        foreach ($chain as $user) {
            if ($user->level <= $this->user->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diff('vip1');
                $this->saveCommission($user->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('vip2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diff('vip3');
                $diff_vip3 -= $diff_vip1 + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
                break;
            }
        }
    }

    private function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    public function buy()
    {
        $award_name = '消费差价';
        $award_type = 11;

        $amount = $this->order->total_pay - $this->order->total_freight;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3']
        ], true);

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;

        foreach ($chain as $user) {

            if ($user->level <= $this->user->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $amount - $this->_diff(UserLevel::$keys['vip1']);
                $this->saveCommission($user->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $amount - $this->_diff(UserLevel::$keys['vip2']);
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $amount - $this->_diff(UserLevel::$keys['vip3']);
                $diff_vip3 -= $diff_vip1 + $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
                break;
            }
        }
    }

    private function _diffx($vip)
    {

        $ratio = (float)UserLevel::find()
                ->where(['value' => $vip])
                ->select(['discount'])
                ->scalar() / 10;

        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = Product::findOne(['id' => $item->product_id])->toArray();
            $sum += ($product['price']) * $item['quantity'];
        }

        return $sum * $ratio;


    }


    // 推荐奖
    // public function recommend()
    // {
    //     $name1 = '推荐奖';
    //     $type1 = 10;
    //
    //     $name2 = '扶持奖励';
    //     $type2 = 20;
    //
    //     $name3 = '出额';
    //     $type3 = 30;
    //
    //     $name4 = '分红';
    //     $type4 = 40;
    //
    //     $amount = $this->order->total_pay - $this->order->total_freight;
    //
    //     $r = Chain::getReferrer($this->order->user_id, true);
    //     if ($r) {
    //         $commission = 0;
    //
    //         // 是否为上级出
    //         $seller = false;
    //
    //         // 购买VIP3
    //         if ($amount >= $this->set->vip3) {
    //             if ($r->level == UserLevel::$keys['vip1']) {
    //                 $commission = $this->set->vip1_3;
    //             }
    //             if ($r->level == UserLevel::$keys['vip2']) {
    //                 $commission = $this->set->vip2_3;
    //             }
    //             if ($r->level == UserLevel::$keys['vip3']) {
    //                 $commission = $this->set->vip3_3;
    //             }
    //         }
    //
    //         // 购买VIP2
    //         else if ($amount >= $this->set->vip2) {
    //             if ($r->quota2 > 0) {
    //                 $seller = true;
    //             } else {
    //                 if ($r->level == UserLevel::$keys['vip1']) {
    //                     $commission = $this->set->vip1_2;
    //                 }
    //                 if ($r->level == UserLevel::$keys['vip2']) {
    //                     $commission = $this->set->vip2_2;
    //                 }
    //                 if ($r->level == UserLevel::$keys['vip3']) {
    //                     $commission = $this->set->vip3_2;
    //                 }
    //             }
    //         }
    //
    //         // 购买VIP1
    //         else if ($amount >= $this->set->vip1) {
    //             if ($r->quota1 > 0) {
    //                 $seller = true;
    //             } else {
    //                 if ($r->level == UserLevel::$keys['vip1']) {
    //                     $commission = $this->set->vip1_1;
    //                 }
    //                 if ($r->level == UserLevel::$keys['vip2']) {
    //                     $commission = $this->set->vip2_1;
    //                 }
    //                 if ($r->level == UserLevel::$keys['vip3']) {
    //                     $commission = $this->set->vip3_1;
    //                 }
    //             }
    //         }
    //
    //         if ($seller && $r->level >= UserLevel::$keys['vip2']) {
    //             // 出货
    //             $this->saveCommission($r->id, $amount, $type3, $name3);
    //             if (!$this->is_reset) {
    //                 if ($amount >= $this->set->vip2) {
    //                     $r->quota2 -= 1;
    //                 } elseif ($amount >= $this->set->vip1) {
    //                     $r->quota1 -= 1;
    //                 }
    //                 $r->save();
    //             }
    //         } else {
    //             $this->saveCommission($r->id, $commission, $type1, $name1);
    //             // 扶持奖励
    //             if ($r->level == UserLevel::$keys['vip3']) {
    //                 $this->saveCommission($r->id, $amount * $this->set->help_ratio / 100, $type2, $name2);
    //             } else {
    //                 // $r2 = Chain::getReferrer($r->id, true);
    //                 // if ($r2 && $r2->level == UserLevel::$keys['vip3']) {
    //                 //     $this->saveCommission($r2->id, $commission * $this->set->help_ratio / 100, $type2, $name2);
    //                 // }
    //             }
    //             // 分红
    //             $list = User::find()
    //                 ->where(['level' => UserLevel::$keys['vip3']])
    //                 ->orderBy(['id' => SORT_ASC])
    //                 ->limit($this->set->profit_num)
    //                 ->all();
    //             if ($list) {
    //                 $commission = $amount * $this->set->profit_ratio / 100 / count($list);
    //                 foreach ($list as $user) {
    //                     $this->saveCommission($user->id, $commission, $type4, $name4);
    //                 }
    //             }
    //         }
    //     }
    //
    // }


    // 保存佣金
    protected function saveCommission($user_id, $balance, $type, $name, $score = 0)
    {
        if ($balance >= 0.01 || $score >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->score = $score;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            if ($score > 0) {
                @ScoreService::score($user_id, $score);
            }

            $account = UserAccount::findOne(['user_id' => $user_id]);

            if ($account) {
                $account->balance += $balance;
                $account->score += $score;
                $account->save();
            }

        }
    }
}